package com.ruoyi.mall.controller;

import java.math.BigDecimal;
import java.util.*;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.utils.ApiResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.mall.service.IMallTimeWithdrawService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.mall.domain.MallTimeOrder;
import com.ruoyi.mall.service.IMallTimeOrderService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 抢购订单Controller
 *
 * @author ruoyi
 * @date 2022-03-01
 */
@RestController
@RequestMapping("/mall/mallTimeOrder")
public class MallTimeOrderController extends BaseController
{
    @Autowired
    private IMallTimeOrderService mallTimeOrderService;

    /**
     * 查询抢购订单列表
     */
    @PreAuthorize("@ss.hasPermi('mall:mallTimeOrder:list')")
    @GetMapping("/list")
    public TableDataInfo list(MallTimeOrder mallTimeOrder)
    {
        startPage();
        List<MallTimeOrder> list = mallTimeOrderService.selectMallTimeOrderList(mallTimeOrder);
        return getDataTable(list);
    }

    /**
     * 导出抢购订单列表
     */
    @PreAuthorize("@ss.hasPermi('mall:mallTimeOrder:export')")
    @Log(title = "抢购订单", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(MallTimeOrder mallTimeOrder)
    {
        List<MallTimeOrder> list = mallTimeOrderService.selectMallTimeOrderList(mallTimeOrder);
        ExcelUtil<MallTimeOrder> util = new ExcelUtil<MallTimeOrder>(MallTimeOrder.class);
        return util.exportExcel(list, "抢购订单数据");
    }

    /**
     * 获取抢购订单详细信息
     */
    @PreAuthorize("@ss.hasPermi('mall:mallTimeOrder:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(mallTimeOrderService.selectMallTimeOrderById(id));
    }

    /**
     * 新增抢购订单
     */
    @PreAuthorize("@ss.hasPermi('mall:mallTimeOrder:add')")
    @Log(title = "抢购订单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MallTimeOrder mallTimeOrder)
    {
        return toAjax(mallTimeOrderService.insertMallTimeOrder(mallTimeOrder));
    }

    /**
     * 修改抢购订单
     */
    @PreAuthorize("@ss.hasPermi('mall:mallTimeOrder:edit')")
    @Log(title = "抢购订单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MallTimeOrder mallTimeOrder)
    {
        return toAjax(mallTimeOrderService.updateMallTimeOrder(mallTimeOrder));
    }

    /**
     * 删除抢购订单
     */
    @PreAuthorize("@ss.hasPermi('mall:mallTimeOrder:remove')")
    @Log(title = "抢购订单", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(mallTimeOrderService.deleteMallTimeOrderByIds(ids));
    }

    @Autowired
    private IMallTimeWithdrawService mallTimeWithdrawService;
    /**
     * 今日数据折线图接口
     *
     * @param
     * @return 单条数据
     */
    @GetMapping("/today/lineChart")
    public AjaxResult todayLineChart() {
        Map<String, Object> queryTodayLineChart = mallTimeOrderService.queryTodayLineChart();
        Map<String,Object> map = new HashMap<>();
        // 订单数
        map.put("orderNum",queryTodayLineChart.get("orderNum"));
        // 购买人数
        map.put("buyerNum",queryTodayLineChart.get("buyerNum"));
        // 当日流水
        map.put("todayRunWater",queryTodayLineChart.get("todayRunWater"));
        return AjaxResult.success(map);
    }

    /**
     * 历史数据折线图接口
     *
     * @param
     * @return 单条数据
     */
    @PostMapping("/history/lineChart")
    public AjaxResult countLineChart(String beginAt, String endAt) {
        Map<String,Object> map = new HashMap<>();
        Date beginTime = null;
        Date endTime = null;
        Calendar c = Calendar.getInstance();
        if (StringUtils.isNotEmpty(beginAt)){
            beginAt = beginAt+" 00:00:00";
            endAt = endAt+" 23:59:59";

            beginTime = DateUtils.parseDate(beginAt);
            endTime = DateUtils.parseDate(endAt);
        }else {
            c.setTime(DateUtils.getNowDate());
            c.add(Calendar.DATE, -30);
            String day = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,c.getTime());
            beginAt = day+" 00:00:00";
            endAt = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,DateUtils.getNowDate())+" 23:59:59";

            beginTime = DateUtils.parseDate(beginAt);
            endTime = DateUtils.parseDate(endAt);
        }

        List<BigDecimal> runWaterList = new ArrayList<>();
        List<BigDecimal> turnoverList = new ArrayList<>();
        List<BigDecimal> sharePriceList = new ArrayList<>();
        List<Integer> dealNumList = new ArrayList<>();
        List<Integer> buyerNumList = new ArrayList<>();
        List<String> dayList = new ArrayList<>();
        while (beginTime.getTime()<=endTime.getTime()){
            String day = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,beginTime);
            beginAt = day +" 00:00:00";
            endAt = day + " 23:59:59";
            dayList.add(day);
            map.put("beginAt",beginAt);
            map.put("endAt",endAt);
            Map<String,Object> cm = mallTimeOrderService.queryHistoryLineChart(map);
            runWaterList.add(new BigDecimal(cm.get("runWaterList").toString()));
            buyerNumList.add(Integer.parseInt(cm.get("buyerNumList").toString()));
            Map<String,Object> cm2 = mallTimeOrderService.queryHistoryLineChart2(map);
            turnoverList.add(new BigDecimal(cm2.get("turnoverList").toString()));
            dealNumList.add(Integer.parseInt(cm2.get("dealNumList").toString()));
            Map<String, Object> cm3 = mallTimeWithdrawService.queryHistoryLineChartSharePrice(map);
            sharePriceList.add(new BigDecimal(cm3.get("sharePriceList").toString()));
            c.setTime(beginTime);
            c.add(Calendar.DATE, 1);
            beginTime = c.getTime();
        }
        Map<String,Object> rm = new HashMap<>();
        // 流水
        rm.put("runWaterList",runWaterList);
        // 营业额
        rm.put("turnoverList",turnoverList);
        // 分佣金额
        rm.put("sharePriceList",sharePriceList);
        // 成交单数
        rm.put("dealNumList",dealNumList);
        // 消费人数
        rm.put("buyerNumList",buyerNumList);
        // 日期
        rm.put("dayList",dayList);
        return AjaxResult.success(rm);
    }

    /**
     * 分销商列表查看总流水
     *
     * @param
     * @return 单条数据
     */
    @GetMapping("/retailerList/seeRunWater")
    public ApiResult seeRunWater(@RequestParam(value="pageNum",defaultValue="1",required = false) Integer pageNum,
                                 @RequestParam(value="pageSize",defaultValue="10",required = false) Integer pageSize,
                                 Long userId) {
        HashMap<String, Object> map = new HashMap<>();
        PageHelper.startPage(pageNum,pageSize);
        List<MallTimeOrder> list = mallTimeOrderService.distributorListViewTotalFlow(userId);
        PageInfo<MallTimeOrder> pageInfo = new PageInfo<>(list);
        map.put("data", pageInfo);
        return ApiResult.ok(map);
    }

    /**
     * 分销商列表查看下级
     *
     * @param
     * @return 单条数据
     */
    @GetMapping("/retailerList/seeSubordinate")
    public ApiResult seeSubordinate(@RequestParam(value="pageNum",defaultValue="1",required = false) Integer pageNum,
                                    @RequestParam(value="pageSize",defaultValue="10",required = false) Integer pageSize,
                                    Long userId) {
        HashMap<String, Object> map = new HashMap<>();
        PageHelper.startPage(pageNum,pageSize);
        List<MallTimeOrder> list = mallTimeOrderService.distributorListViewSubordinate(userId);
        PageInfo<MallTimeOrder> pageInfo = new PageInfo<>(list);
        map.put("data", pageInfo);
        return ApiResult.ok(map);
    }

    /**
     * 取消抢购订单
     */
    @PutMapping( "/cancelOrderByUserIdOrderId")
    public AjaxResult cancelOrderByUserIdOrderId(@RequestBody MallTimeOrder mallTimeOrder)
    {
        mallTimeOrderService.cancelOrderByUserIdOrderId(mallTimeOrder.getSellerUserId(), mallTimeOrder.getId());
        return AjaxResult.success();
    }
}
